#!/usr/bin/python

import dbus
import random
from constants import *
import logging



# Own constants
TREE_ID = "http://nepomuk.semanticdesktop.org"
logger = logging.getLogger("pyfuncs")
logger.setLevel(logging.DEBUG+1)


def random_string(nb_chars):
	string = ""
	for i in range(nb_chars):
		string += random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
	return string
	
############################################################

# not used at the moment
def node2string(node):
	if node[0] == NODE_EMPTY:
		return "(empty)"
	elif node[0] == NODE_RESOURCE:
		return "<" + node[1] + ">"
	elif node[0] == NODE_LITERAL:
		return "\"" + node[1] + "\"^^" + node[3]
	elif node[0] == NODE_BLANK:
		return "_:"+node[1]

############################################################

def makeOntologyUriFromUserId(user_id, ontology_name):
	
	return "nepomuk:" + user_id + "/resources/ontologies/" + ontology_name

############################################################

def makeUriWithUserId(user_id, resource_name):
	
	return "nepomuk:" + user_id + "/resources/pimo/" + resource_name
	
############################################################

# turns a "user-formatted" name (with spaces) into its equivalent in "uri-formatted" name.
# e.g. kill_spaces("is supervised by") => "isSupervisedBy"
def kill_spaces(user_formatted_name):
	
	st = "".join(	user_formatted_name.title().split(" ") )
	st = st[0].lower()+st[1:len(st)]
	return st

############################################################

# gets the ending part of long_name, the one located after the '#' character.
def getName(long_name):
	
	sharp_index = long_name.rfind("#")
	if sharp_index == -1:
		return long_name
	else:
		return long_name[sharp_index+1:len(long_name)]

############################################################

def makeExistenceWhereClause(resource, relation, object):
	
	st = "{ "
	st += "<" + resource + "> ?relation <" + object + "> "
	st += "FILTER (?relation = <"+relation+">) "
	st += "}"
	return st

############################################################

class rdf_gen:
	
	def __init__(self, file_name):
		self.file = file( file_name, "w" )
		self.tag_group_no = 1

############################################################

	def write_tags(self, tags):
		
		self.footer = ""
		
		current_uri = ""
		self.tag_group_no = 1
		tag_no = -1
		
		self.write_header()
		
		while tags.next():
			uri = tags.current()[0]["uri"][1]
			tag = tags.current()[0]["tag"][1]
			desc = tags.current()[0]["desc"][1]
			
			# information about the uri (if it is new)
			if uri != current_uri:
				
				if tag_no != -1:
					self.register_info_in_footer(tag_no - 1)
					self.tag_group_no += 1
					
				# prepare new information
				current_uri = uri
				#self.file.write("\t<RDF:Description RDF:about=\"" + TREE_ID + "/tag" + str(self.tag_group_no) + "\">\n")
				#self.file.write("\t\t<Annotation:item>" + uri + "</Annotation:item>\n")
				#self.file.write("\t</RDF:Description>\n\n")
				tag_no = 1
				
			# information about the nth tag and description of this tag
			self.file.write("\t<RDF:Description RDF:about=\"" + TREE_ID + "/tag" + str(self.tag_group_no) + "-" + str(tag_no) + "\">\n")
			self.file.write("\t\t<Annotation:item>" + tag + "</Annotation:item>\n")
			self.file.write("\t\t<Annotation:info>" + desc + "</Annotation:info>\n")
			self.file.write("\t</RDF:Description>\n\n")
			
			tag_no += 1
			
			logger.debug(uri)
			logger.debug(tag)
			logger.debug(desc)
		
		if tag_no != -1: # it means that there is not any tag.
			self.register_info_in_footer(tag_no - 1)
		self.write_footer()
		
		self.file.close()
		
############################################################

	def write_header(self):
		self.file.write("<?xml version=\"1.0\"?>\n\n")
		self.file.write("<RDF:RDF xmlns:RDF=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:Annotation=\"" + TREE_ID + "/rdf#\">\n\n")
		
		self.file.write("\t<RDF:Description RDF:about=\"" + TREE_ID + "/tags\">\n")
		self.file.write("\t\t<Annotation:item>" + TREE_ID + "</Annotation:item>\n")
		self.file.write("\t</RDF:Description>\n\n")
		
############################################################

	def write_footer(self):
		#self.file.write("\t<RDF:Seq RDF:about=\"" + TREE_ID + "/all-tags\">\n")
		#self.file.write("\t\t<RDF:li>\n")
		
		self.file.write("\t<RDF:Seq RDF:about=\"" + TREE_ID + "/tags\">\n")

		self.file.write(self.footer)
		
		self.file.write("\t</RDF:Seq>\n\n")
		
		#self.file.write("\t\t</RDF:li>\n")
		#self.file.write("\t</RDF:Seq>\n\n")
		
		self.file.write("</RDF:RDF>\n")
		
############################################################

	def register_info_in_footer(self, nb_tags):
		# register the information for the tree view ("close" the current uri)
		for i in range(nb_tags):
			self.footer += "\t\t\t\t<RDF:li RDF:resource=\"" + TREE_ID + "/tag" + str(self.tag_group_no) + "-" + str(i+1) + "\"/>\n"
			
############################################################

	# An item is a tuple containing the values for one particular piece of information
	def write_list(self, info_type, item_list):
		
		self.footer = ""
		
		# The info_type represents the types of information contained in each item of the item_list, e.g. ["Annotation:item", "Annotation:url"].
		
		item_no = 1
		
		self.write_header()
		
		for item in item_list:
			
			# keys information for the nth element (e.g. tag and description of the current tag
			self.file.write("\t<RDF:Description RDF:about=\"" + TREE_ID + "/tag" + str(item_no) + "\">\n")
			for i in range(len(item)):
				self.file.write("\t\t<" + info_type[i] + ">" + item[i] + "</" + info_type[i] + ">\n")
				#self.file.write("\t\t<Annotation:info>" + desc + "</Annotation:info>\n")
			self.file.write("\t</RDF:Description>\n\n")
			
			#self.register_info_in_footer(tag_no - 1)
			self.footer += "\t\t<RDF:li RDF:resource=\"" + TREE_ID + "/tag" + str(item_no) + "\"/>\n"
			
			item_no += 1
		
		self.write_footer()
		
		self.file.close()
		
		return 0
			

		
	